/*
 * @Author: mjjh
 * @LastEditTime: 2023-04-15 23:27:47
 * @FilePath: \chatgpt-shuowen\src\store\modules\auth\index.ts
 * @Description: 存储用户数据
 */
import { defineStore } from 'pinia'
import { getToken, removeToken, setToken } from './helper'
import { store } from '@/store'
import { login as loginApi } from '@/api/login';
import { LoginData } from '@/api/types';
import { to } from 'await-to-js';


export interface AuthState {
  token: string | undefined
}

export const useAuthStore = defineStore('auth-store', {
  state: (): AuthState => ({
    token: getToken(),
  }),
  actions: {
    async login(userInfo: LoginData): Promise<void> {
      const [err, res] = await to(loginApi(userInfo));
      console.log(res);
      if (res && res.code == 200) {
        const data = res.data;
        let token = data.access_token != null && data.access_token != "" ? data.access_token : data.token;
        setToken(token);
        return Promise.resolve();
      }
      if (res == null) {
        return Promise.reject("后台错误,请联系管理员");
      }
      return Promise.reject(res.msg);
    },
    setToken(token: string) {
      this.token = token
      setToken(token)
    },

    removeToken() {
      this.token = undefined
      removeToken()
    },
  },
})

export function useAuthStoreWithout() {
  return useAuthStore(store)
}
